<?php

class AutoApprovalPlugin extends CorePlugin{
    public function __construct() {
        Yii::import('ext.plugins.AutoApproval.models.SettingAutoApproval');
        
        Yii::app()->plugin->onMemeBeforeSave = array($this, 'set_approval');
        Yii::app()->plugin->onMemeAfterSave = array($this, 'redirect');
        Yii::app()->plugin->onBeforeActions = array($this, 'add_actions');
        
        if(Yii::app()->controller->isBackend) {
            Yii::app()->plugin->onBeforeMenuRender = array($this, 'add_menu');
        }
    }
    
    public function set_approval($e) {
       $setting = Settings::value('autoapproval_active');
        
        if($setting) {
            $e->sender->is_active = $setting;
        }
    }
    
    public function redirect($e) {
       $setting = Settings::value('autoapproval_active');
        
        if($setting) {
            Utility::setFlash(Yii::t('yii', 'Your meme is active!'), 'success');
            Yii::app()->request->redirect(Yii::app()->homeUrl);
        }
    }
    
    public function add_menu($e) {
        if($e->params['menu'] == 'admin-menu') {
            foreach(Yii::app()->plugin->menu['admin-menu']['items'] as $i => &$item) {
                if(strpos($item['label'], 'Settings')) {
                    $item['items'][] = array(
                        'label' => '<i class="icon-check"></i> Auto Approval',
                        'url' => array('settings/auto-approval'),
                    );
                }
            }
        }
    }
    
    public function add_actions($e) {
        if($e->sender->isBackend && $e->sender->id == 'settings') {
            $e->sender->actions['auto-approval'] = array(
                'class' => 'ext.plugins.AutoApproval.actions.AutoApprovalSettingAction'
            );
        }
    }
}